<template>
	<view class="pBox" v-show="showStatus" :style="{'overflow-y':showTask==true?'none':'auto'}">
		<view class="banner">
			<view class="banner_image">
				<image :src="setData.banner" mode="widthFix"></image>
			</view>
			<view class="theme_color" :style="{'background': setData.bgcolor || '#FFBE9E'  }"> </view>
		</view>
		<view class="header_box">
			<span class="share" type="default" @click="nextPage(0)">分享活动</span>
			<span class="prize" type="default" @click="nextPage(1)">我的奖品</span>
		</view>
		<view class="container" :style="{'background': setData.bgcolor || '#FFBE9E'  }">
			<view class="banner_bg" v-show="setData.show_winner && activityText.winners.length>0">
				<view class="name_banner" id="banner" :style="[{'animation-duration':bannerDelay,'width':bannerWidth+'px'}]">
					<view class="item" :class="{'banner_item':true}" v-for="(item,index) in activityText.winners" :key="index">
						<view class="avatr" >
							<image :src="item.avatar"   @error="imageError($event, index)"/>
						</view>
						<span>{{item.message}}</span>
					</view>
				</view>
			</view>
			<view class="turnTable" :style="{'margin-top':setData.show_winner && activityText.winners.length>0 ?'-114rpx':'-26rpx' }">
				<turnTable ref="tunrTable" :prizeList="prizeList" :status="pageStatus" :prize="prizeId" @start="getPrize" @back="handlerGuafinish"></turnTable>
				<view class="chair">
					<image :src="qiniuUrl+'chair.png'" mode="widthFix"></image>
					<view class="getMore">
						<image class="more" :src="qiniuUrl+'getMore.png'" mode="widthFix"></image>
						<!-- <image class="moretext" src="@/static/turnTable/moretext.png" mode="widthFix"></image> -->
						<view class="moretext" @click="openTaskCenter">
							<span v-if="activityText.has_task">去赚更多抽奖机会</span>
							<span v-else>剩余{{chance<0?0:chance}}次抽奖机会</span>
						</view>
						<image v-if="checkPlat(true) && activityText.has_task" class="text" :src="qiniuUrl+'times.png'" mode="widthFix"></image>
						<view v-if="checkPlat(true) && activityText.has_task" class="text_box" >
							您当前剩余{{chance<0?0:chance}}次抽奖机会
						</view>
					</view>
				</view>

			</view>
			<view class="content_box">
				<!--  -->

				<view class="nums" v-if="setData.show_data">
					<view class="num">
						<span>{{activityText.view_num || 0}}</span>
						<span>浏览量</span>
					</view>
					<view class="divider"></view>
					<view class="num">
						<span>{{activityText.play_num || 0}}</span>
						<span>参与量</span>
					</view>
					<view class="divider"></view>
					<view class="num">
						<span>{{activityText.win_num || 0}}</span>
						<span>中奖数</span>
					</view>
				</view>
				<view v-if="setData.service_open">
					<service></service>
				</view>
				<view v-for="(item,index) in rules" :key="index">
					<view class="info">
						<view>
							<view></view>
							<span>{{item.title}}</span>
							<view></view>
						</view>
						<view>
							 <view class="dec" v-html="item.content">{{item.content}}</view>
						 </view>
					</view>
				</view>
				<view class="footer_name" v-if="setData.copyright!=''">
					{{setData.copyright}}
				</view>
				<view v-else style="height: 40rpx;">

				</view>
			</view>
		</view>
		<view class="getMoreTimes" v-if="(activityText.has_task && taskMenuData.length>0) || isframe  ">
			<img :src="setData.task_float" @click="openTaskCenter"></img>
		</view>
		<taskCenter :show="showTask" :topImage="setData" :list="taskMenuData" @close="handlerCloseTaskCenter" @finish="handlerTaskFinish"></taskCenter>
		<modal v-if="modalData.show" :showType="modalData.type" :data="serviceData" @back="handlerInitGua" @close="handlerCloseModal"></modal>
		<modal v-if="noTimes" :showType="10" :data="serviceData"  @close="noTimes=false"></modal>
		<advertise  :data="advSet" @close="closeAdv"></advertise>
		<share v-if="showShare" :data="data" @close="showShare=false"></share>
		<guide></guide>
		<help :data="setData" v-if="showHelpModal" @hideMissionModal="hideModal"></help>
		<collectPhone  :data="data" ></collectPhone>
	</view>
</template>

<script>
	import {getGuess,ActivityInfo,chance,activityText,taskList} from '@/api/api.js'
	import {getActivityPrize} from '@/api/turnTable.js'
	import {mapGetters} from 'vuex'
	import {LoginApp,checkLogin,getSystemInfo,isWeiXin,isQianfan,checkPlatform,proxyShareFun,newJumpUrl} from '@/until/QFH5.js'
	import {formatTime} from '@/until/tool.js'
	import watermarkOption from '@/until/water.js'
	import * as frameJs from  '@/model/frameData.js'
	import help from "../../../components/taskCenter/help";
	export default{
		components: {help},
		computed:{
			...mapGetters([ 'loginInfo', 'qiniuUrl', 'guide', 'updateTask','showCollectPhone']),
		},
		data(){
			return{
				advSet:{},//控制广告
				bannerDelay:'20s',//文字公告
				bannerWidth:'0px',//文字公告
				pageStatus:-1,//页面状态(刮奖蒙层显示类别) 3：图片

				showTask:false,//任务中心
				taskMenuData:[],//任务中心菜单

				modalData:{show:false,type:2},//中奖弹窗
				serviceData:{},//弹窗使用的所有信息 中奖内容
				data:{ start_time:0 },//页面所有数据
				setData:{},//基础设置参数
				rules:[],//商家说明
				actid:1,//活动id
				chance:-1,//刮奖次数
				activityText:{ view_num:0, winners:[] },//动态文本数据
				taskid:156,//任务id
				taskData:null,//任务list

				showTaskModal:false,//弹窗任务
				showShare:false,//分享
				noTimes:false,//无次数
				isMoreTask:false,//是否还有未完成的任务,
				isframe:false,//被后端引用
				frameData:{ data:{ settings:{ win_popup:"" } } },
				showStatus:false,//v-clovk
				guaStatus:false,//刮奖层状态，

				prizeList:null,
				prizeId:-1,
				prizeInfo:'',//开奖信息
				
				frameInitRequest:false,//frame接口节流
				
				turnTableStatus:false,
				showHelpModal:false,
			}
		},
		methods:{
			//禁止划动
			moveHandle(){},
			//隐藏
			hideModal() {
			  this.showHelpModal = false
			},
			//图片错误
			imageError(e, index){
				this.activityText.winners[index]['avatar'] = '/static/guess/avatar.png'
			},
			//关闭广告
			closeAdv(){
				this.advSet.start_ad_show = false
				this.advSet.popup_ad_show = false
			},
		    nextPage(val){
				if(val){
					let callback=()=>{
						let url ='/plugin/pages/guess/prize?id='+this.actid
						// #ifdef MP-WEIXIN
						url = '../guess/prize?id='+this.actid
						// #endif
						this.$navigateTo({ url:url})
					}
					this.getAuth(callback,null,false,true)
				}else{
					this.showShare = true
				}
			},
			//
			login(){
				if(this.checkPlat()){
					LoginApp()
				}
			},
			//检查平台
			checkPlat(val){
				let plat = checkPlatform(val)
				if(!plat&&!val){
					this.$store.dispatch('setGuideShow',4)
				}
				return plat
			},
			//计算当前次数
			sumChance(){
				let noFinish = 0
				this.taskMenuData.forEach(item=>{
					if(item.is_finish==false){
							noFinish++
					}
				})
				if(noFinish>0){this.isMoreTask = true}
				else{this.isMoreTask = false}

			},
			//所有前置条件
			async getAuth(callback=()=>{},back=()=>{},isInit=false,isNeglect=false){
				let {isWechat,phone} = this.guide
				// console.log('加载当前回调',callback(),back())
				if(this.checkPlat(isInit)){
					if(!isNeglect&&this.pageStatus==0){
						uni.showToast({ title:'活动还没开始呢', icon:'none' })
						return
					}
					if(!isNeglect&&this.pageStatus==1){
						uni.showToast({ title:'活动已经结束了', icon:'none' })
						return
					}
					let loginStatus = await checkLogin()
					if(!loginStatus){
						this.login()
						return
					}
					//收集信息
					if (this.data.collect == 1 && this.showCollectPhone == '' && isWeiXin()) {
						this.$store.commit('SET_SHOWCOLLECT', true)
						return
					}
					if(isQianfan()){
						if(!isWechat){
							this.$store.dispatch('setGuideShow',1)
							back()
							return
						}
						if(phone==""){
							this.$store.dispatch('setGuideShow',2)
							if(this.guaStatus){
								this.resetGua()
								this.guaStatus = false
							}
							return
						}
					}
					if(!isNeglect&&this.chance==0){
						this.sumChance()
						if(this.activityText.has_task && this.taskMenuData.length>0 && this.isMoreTask){
							uni.showToast({ title:'试试以下方式获得更多刮奖次数', icon:'none', duration:3000 })
							this.showTask = true
						}else{
							this.noTimes = true
						}
						return
					}
					callback()
				}
			},
			//开奖
			getPrize(){
				this.guaStatus = true
				if(this.turnTableStatus){
					return
				}
				this.turnTableStatus = true
				let callback = ()=>{
					if(this.chance<=0){
						this.sumChance()
						if(this.activityText.has_task && this.taskMenuData.length>0 && this.isMoreTask){
							uni.showToast({ title:'试试以下方式获得更多刮奖次数', icon:'none', duration:3000 })
							this.showTask = true
						}else{
							this.noTimes = true
						}
						return
					}


					
					getGuess({actid:this.actid}).then(res=>{
						console.log(res.data)
						this.$refs.tunrTable.startAnimation()
						if(res.code==0){
							if(res.data.prize){
								this.prizeId = res.data.prize.id
							}else{
								this.prizeId = 0
							}
							this.prizeInfo = res

						}else{
							this.resetGua()
							uni.showToast({ title:res.text, icon:'none', duration:3000 })
							if(this.activityText.has_task && this.isMoreTask){
								if(this.chance==0){
									this.showTask = true
								}
							}
						}
					})
				}
				let otherback = ()=>{this.resetGua()}
				this.getAuth(callback,otherback)
			},
			//刮奖结束
			handlerGuafinish(val){
				let res = this.prizeInfo
				let _this = this
				console.log('抽到了',res)
				this.serviceData = res.data.prize || {}
				this.serviceData.win_popup = this.setData.win_popup
				setTimeout(()=>{
						_this.modalData.show=true
						if(res.data.ret==1){
							_this.modalData.type=2

						}else{
							_this.modalData.type=3
						}
						_this.turnTableStatus = false
				},500)
				
				this.getActivity()
				this.getChance()
			},
			//关闭按钮
			handlerCloseModal(){
				this.modalData.show = false
			},
			//重置刮奖状态
			resetGua(){
				// console.log('reset')
				console.log('重置')
				this.guaStatus = false

			},
			//在玩一次
			handlerInitGua(){
				this.modalData.show = false
				this.resetGua()
			},
			openTaskCenter(){
				let callback = ()=>{
					this.showTask = !this.showTask
				}
				this.getAuth(callback)
			},
			//关闭任务
			handlerCloseTaskCenter(val){
				this.showTask = val
			},
			//完成任务
			handlerTaskFinish(val){
				if(val && val.type=='share')
					this.showShare = true
				this.initTask()
				this.getChance()
			},
			async init(){

				let res = null
				let nowTime =  Math.floor(new Date()/1000)

				if(!this.isframe){
						res = await ActivityInfo({actid:this.actid})
				}else{
					res = this.frameData
				}
				if(res.code == 0){
					this.$setTitle(res.data.title)
					uni.setStorageSync('title',res.data.title)
					this.data = res.data
					if(!this.isframe){
						this.initTableData()
					}
					let _this = this
					this.$nextTick(()=>{
						let token = localStorage.getItem(_this.actid+'bearerToken') || null
						if(token!=null && _this.$store.state.long==0 && _this.$store.state.lat==0  &&_this.data.area && _this.data.area.type==3){
							_this.$store.dispatch('getPos')
							window.getLocationCallBackFun=()=>{}
						}
					})
					// #ifdef H5
					if(res.data.status==0){
						watermarkOption.set('活动未发布')
					}
					// #endif
					let {settings} = res.data
					uni.setStorageSync('platform',JSON.stringify(settings.platform))
					this.setData = settings
					this.advSet = settings
					//规则排序
					this.rules = []
					settings.sort.forEach(item=>{
						if(res.data[item]){
							let obj = {title:this.formartText(item),content:res.data[item]}
							this.rules.push(obj)
						}
					})
					this.$store.dispatch('serviceInfo',settings)

				}
				if(nowTime<res.data.start_time){
					this.pageStatus = 0
				}else if(nowTime>res.data.expire_time){
					this.pageStatus = 1
				}else{
					this.pageStatus = 2
				}
				let data = res.data
				proxyShareFun(data.settings.title,data.settings.image,data.settings.desc,window.location.href)
			},
			formartText(val){
				let {business_intro,activity_rules,prize_intro} = this.setData.custom_desc_key
				switch(val){
					case 'business_intro':return business_intro!=''?business_intro:'商家介绍'
					case 'activity_rules':return activity_rules!=''?activity_rules:'活动规则'
					case 'prize_intro':return prize_intro!=''?prize_intro:'奖品介绍'
				}
			},
			//设置公告速度
			initCss(){
				let _this = this
				let width = 0
				uni.createSelectorQuery().in(this).selectAll(".banner_item").boundingClientRect(dom=>{
					if(dom.length>0){
						dom.forEach(item=>{ width += item.width })
						uni.getSystemInfo({
							success(res) {
								let pix = res.windowWidth/750
								//10右边间距
								_this.bannerWidth=width+pix*10*(dom.length-1)
								let pixWidth = 750  //*pix
								let nWidth = _this.bannerWidth>pixWidth?_this.bannerWidth:pixWidth
								_this.bannerDelay = parseInt(nWidth/30)+"s"
							}
						})
					}
				}).exec();
			},
			//初始化转盘数据
			initTableData(){
				getActivityPrize({actid:this.actid}).then(res=>{
					this.prizeList = res.data
					let {unwin_image,unwin_text} = this.data.settings
					let url =unwin_image==''? this.qiniuUrl+'goodluck02.png':unwin_image
					let obj = {
						title:'谢谢参与',
						id:0,
						type:4,
						image:url,
						text:unwin_text==''?'祝你好运':unwin_text
					}
					this.prizeList.push(obj)
					this.frameInitRequest = false
				})
			},
			//获取刮奖次数
			getChance(){
				chance({actid:this.actid}).then(res=>{
					this.chance = res.data.num || 0
				})
			},
			//获取动态文本
			getActivity(){
				activityText({actid:this.actid}).then(res=>{
					if(res.code ==0){
						this.activityText = res.data
						let _this = this
						this.showStatus = true
						setTimeout(()=>{
							_this.initCss()
						},300)
						if(res.data.has_task && this.taskMenuData.length==0){
							this.initTask()
						}
					}
				})
			},
			initTask(){
				taskList({actid:this.actid}).then(res=>{
					this.taskMenuData = res.data
				})
			},
			//被当做iframe引用时处理数据
			setIframeData(){
				let _this = this
				window.addEventListener('message',function(e){
					let data = e.data
					//强制兼容后台数据
					_this.frameData={ code:0, data:data }
					let {settings}=data
					let {unwin_image,unwin_text} =settings
					let url = unwin_image
					let obj = {
						title:'谢谢参与',
						id:0,
						type:4,
						image:url,
						text:unwin_text==''?'祝你好运':unwin_text
					}
					let obj2 = {
						title:'模拟一等奖',
						id:20,
						type:2,
						image:_this.qiniuUrl+'goodluck01.png',
					}
					_this.prizeList = []
					_this.prizeList.push(obj)
					_this.prizeList.push(obj2)
					console.log('postmessgae',data['prize_intro'])
					_this.activityText={
						view_num:settings.view_num,
						play_num:settings.play_num,
						win_num:settings.win_num,
						winners:[{avatr:"",message:'仅供展示使用'},{avatr:"",message:'仅供展示使用'},{avatr:"",message:'仅供展示使用'},{avatr:"",message:'仅供展示使用'}]
					}
					
					
					let {popup} = data
					switch(popup){
						case 'win_popup':
							_this.serviceData = { id: 116, redid: 0, title: "示例奖品", type: 2, }
							_this.serviceData.win_popup = _this.setData.win_popup
							_this.modalData.show=true
							_this.modalData.type=2
							break;
						case 'closewin_popup':
							_this.modalData.show=false
							break;
						case "task_popup":
							_this.taskMenuData = frameJs.taskMenuData
							_this.showTask=true
							break;
						case "closetask_popup":
							_this.showTask=false
							break;
						default:break;
					}
					
					_this.init()
					console.log('data.slug',data.slug)
					if(data.slug!="" && !_this.frameInitRequest){
						console.log('data.slug','刷新接口')
						_this.frameInitRequest==true
						_this.actid = data.slug
						
						// _this.initTableData()
						
						
					}
					
					
					
					setTimeout(()=>{ _this.initCss() },100) },false);
			},
		},
	 	mounted() {
			// #ifdef MP-WEIXIN
			this.actid = "RtfgCxtAMC"
			// #endif

			if(!this.isframe){
				this.init()
				this.getActivity()
				// this.initTableData()

				let getChanceback = ()=>{
					// console.log('回调被执行了')
					this.getChance()
				}
				this.getAuth(getChanceback,null,true)
			}
			
			let code = uni.getStorageSync(this.actid+'Invite') || 0
			if(code != 0 ){
				this.showHelpModal = true
			}
		},
		created() {
			this.actid =uni.getStorageSync('actid')
			this.$store.commit('SETACTIVITYNAME','wheel')
			let web  = uni.getStorageSync('WEB') || null
			if(web){
				this.showStatus = true
				this.isframe  = true
				this.actid = uni.getStorageSync('atcid') || null
				this.setIframeData()
			}
		},
		watch:{
		},
		onShow() {
			console.log('触发show')
			this.$setTitle(this.data.title || '')
			let taskStatus =  uni.getStorageSync(this.actid+'taskStatus') || null
			if(taskStatus!=null){
				console.log('触发强刷')
				uni.setStorageSync(this.actid+'taskStatus',null)
				this.getChance()
				this.initTask()
			}
		},
		onLoad(op){		

		},

	}
</script>

<style lang="scss" scoped>
	@import "./wheel.scss"
</style>
